package com.ruoyi.project;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.GoogleAuthenticatorUtils;
import org.apache.shiro.crypto.hash.Hash;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Random;

public class TestString {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    public static void main(String args[]){
        System.out.println( genHMAC("Thu, 18 Feb 2021 08:18:14 GMT\n" +
                "/v0.1/upload\n" +
                "POST\n" +
                "{\"path\":\"/guard/empty\",\"policyType\":\"upload\",\"role\":\"admin\",\"scope\":1,\"uid\":\"505459\"}", "nWu79QqNQAW9g53Ap7Gi5h7Rd5Wn0ucC"));

    }

    public static String genHMAC(String data, String key) {
        byte[] result = null;
        try {
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            //用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac = mac.doFinal(data.getBytes());
            return byte2hex(rawHmac);
//            result = Base64.encodeBase64(rawHmac);

        } catch (NoSuchAlgorithmException e) {
            System.err.println(e.getMessage());
        } catch (InvalidKeyException e) {
            System.err.println(e.getMessage());
        }
        if (null != result) {
            return new String(result);
        } else {
            return null;
        }
    }
    //二行制转字符串
    public static String byte2hex(byte[] b)
    {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }
}
